package com.jxj.study.controller;

import com.jxj.study.domian.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IContext;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
public class HtmlTestController {
    private final Logger logger = LoggerFactory.getLogger(HtmlTestController.class);

    @RequestMapping("/toParent")
    public String toParent(Integer appType, Model model){
        model.addAttribute("appType",appType);
        return "AEmpEntPromise/parent";
    }

    @RequestMapping("/promise")
    public void promise(Integer appType, HttpServletRequest request, HttpServletResponse response){
        System.out.println(appType);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", "zhang三");
        IContext ctx = new WebContext(request,response,request.getServletContext(), Locale.CHINESE,dataMap);
        TemplateEngine engine = new TemplateEngine();
        String process = engine.process("AEmpEntPromise/promise", ctx);
        System.out.println(process);
        try {
            response.setCharacterEncoding("UTF-8");
            //通过响应头，设置浏览器也是用UTF-8
            response.setHeader("Content-Type","text/html;charset=UTF-8");
            response.getWriter().write(process);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = {"/indexPage"})
    public String indexData() {
        logger.info("我的日志");
        return "main";
    }

    @RequestMapping(value = {"/search"}, method = RequestMethod.POST)
    @ResponseBody
    public List<User> search(String id, String query) {
        List<User> users = null;
        User user = null;
        try {
            users = new ArrayList<>();
            user = new User();
            if (id != null && query != null) {
                System.out.println("id ==== " + id + "query === " + query);
                user.setId(id);
                user.setName(query);
                user.setPassword(id + query);
            }
            if ("1".equals(query)){
               double d = 1/0;
            }
        } catch (Exception e) {
            logger.error("错误信息===》"+e.getMessage());
            e.printStackTrace();
        }
        users.add(user);
        return users;
    }
}
